<script setup lang='ts'>
import { useUserStore } from '@/stores'
import { CodeService } from '@/api/public/util'
import type { IUser_Register } from '@/api/Auth/type'

const userStore = useUserStore()
const router = useRouter()

const formModel = ref<IUser_Register>({
  username: '',
  password: '',
  email: '',
  code: '',
})
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '长度为6个字符', trigger: 'blur' },
  ],
})
const formRef = ref()

const disabled2 = ref(false)
const yz = ref({
  total: 60,
  curry: 60,
  timer: null as number | null,
})
//发送验证码
const onSend = () => {
  // 禁用按钮，确保快速点击时不会重复触发
  disabled2.value = true;

  try {
    // 在此处，如果验证不通过，error 将会是 false
    formRef.value.validateField('email', async (error: boolean) => {
      if (!error) {
        // 如果邮箱验证失败，提示用户输入邮箱
        ElMessage.error('请输入邮箱地址');
      } else {
        // 如果有定时器正在运行，防止重复点击
        if (yz.value.timer) {
          ElMessage.info('验证码正在发送，请稍后再试');
          return;
        }

        // 如果倒计时已经结束（curry == total），就重新发送验证码
        if (yz.value.curry === yz.value.total) {
          // 调用验证码服务
          await CodeService(formModel.value.email);
          ElMessage.success('验证码已发送，十分钟以内有效, 请注意查收');

          // 开启定时器，倒计时
          yz.value.timer = setInterval(() => {
            yz.value.curry--;
            if (yz.value.curry <= 0) {
              // 倒计时结束，清除定时器
              clearInterval(yz.value.timer!);
              yz.value.timer = null;
              yz.value.curry = yz.value.total;
            }
          }, 1000);
        } else {
          // 如果定时器还在运行，提示用户稍后再试
          ElMessage.info(`请稍等，验证码将在 ${yz.value.curry} 秒后可重新发送`);
        }
      }
    });
  } finally {
    // 在执行完成后恢复按钮状态，避免点击间隔过快
    setTimeout(() => {
      disabled2.value = false;
    }, 1000); // 这里设置了 1 秒的延迟，避免点击过快
  }
};

const disabled = ref(false)
const onSubmit = async () => {
  await formRef.value.validate()
  disabled.value = true
  try {
    await userStore.register(formModel.value)
    ElMessage.success('注册成功')
    router.push('/login')
  } catch (err) {
    ElMessage.error('注册失败')
  } finally {
    disabled.value = false
    clearInterval(yz.value.timer!)
    yz.value.timer = null
    yz.value.curry = yz.value.total
    formRef.value.resetFields()
  }
}
</script>
<template>
  <div class="login">
    <div class="top">
      <h1>
        <img src="@/assets/images/logo2.jpg" alt="" />
        <span>注册成为快聊的一员吧</span>
      </h1>
    </div>
    <div class="bottom">
      <el-form
        autocomplete="off"
        :model="formModel"
        :rules="rules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formModel.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formModel.email" placeholder="请输入邮箱">
            <template #append>
              <el-button :disabled="disabled2" @click="onSend">{{
                yz.total === yz.curry ? '获取验证码' : yz.curry + 's后重新发送'
              }}</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="formModel.code" placeholder="请输入验证码"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="formModel.password"
            show-password
            type="password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="onSubmit" type="primary" style="width: 100%">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="desc">
      <span>已有账号,</span>
      <router-link to="/login">去登陆</router-link>
    </div>
  </div>
</template>
<style scoped lang='scss'>
.login {
  border: 1px solid #ccc;
  border-radius: 3%;
  box-shadow: 0 0 1px #ccc;
  padding: 30px 50px 30px 30px;
  background-color: #fff;
  .top {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 20px 0;
    h1 {
      display: flex;
      align-items: center;
      img {
        width: 50px;
        height: 50px;
        object-fit: cover;
        margin-right: 10px;
      }
      span {
        font-size: 20px;
        letter-spacing: 2px;
        font-weight: 500;
      }
    }
  }
  .bottom {
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  .desc {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 20px;
    span {
      margin-right: 10px;
    }
  }
}
</style>